package com.bxd.baodan.probe;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.Settings;

import com.google.gson.Gson;
import com.bxd.baodan.probe.bean.AppInstallInfo;
import com.bxd.baodan.probe.bean.ContactsInfo;
import com.bxd.baodan.probe.bean.DeviceInfo;
import com.bxd.baodan.probe.bean.LocationInfo;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.Utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/12/8.
 */

public class Probe {

    /*
    * 回传信息
    1. 应用列表
    2. 手机基础信息 （型号、IMEI、唯一标识等）
    3. 通讯录（特征值，不上传原始通讯录，原始通讯录直接MD5）
    4. 当前手机号（不一定能拿到，可以看看sim卡信息）
    5. 短信（特征值，二期再考虑，比如只按关键字统计下个数，例：银行：10；外卖：20）*/
    //appList
    // phoneType  IMEI  标识
    //contacts 联系人
    //phone
    //message
    public static final String KEY = "xbxiH4QWBPHRXvm0";
    public String platform;
    public String loginUser;
    public String version;
    public List<ContactsInfo> contactList;
    public List<AppInstallInfo> appList;
    public DeviceInfo deviceInfo;
    public LocationInfo location;

    public Probe(Context context) {
        platform = "com.bxd.baodan";
        contactList = getContacts(context);
        appList = getInstallInfo(context);
        deviceInfo = getDeviceInfo(context);
      location = getLocationInfo(context);
    }


    public static void getProData(Context context,String phone) {
        Probe probe = new Probe(context);
        probe.platform = "com.bxd.baodan";
        probe.loginUser = phone;
        probe.contactList = getContacts(context);


        probe.appList = getInstallInfo(context);

        probe.deviceInfo = getDeviceInfo(context);
        probe.location = getLocationInfo(context);
        String info = new Gson().toJson(probe);
        try {
            byte[] encryptResult =AESEncode. encrypt(info,KEY );
            String encryptResultStr = AESEncode.parseByte2HexStr(encryptResult);

            ProbeNetUtil netUtil = new ProbeNetUtil(context, "https://tigris.bxd365.com/message/post/");
            netUtil.setParams("topic", "probe:BXD_APP_STATISTIC_INFO");
            netUtil.setParams("app_id", "probe");
            netUtil.setParams("object", encryptResultStr);
            //参数并没有加完整,部分参数在PreNetUtil#md5Map()
            netUtil.postRequest("", new ProbeNetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    LogUtil.e("probe response data: " + result);
                }
            });

        } catch (Exception e) {
            //java.lang.Exception: java.security.InvalidAlgorithmParameterException: IV must be 8 bytes long.
            e.printStackTrace();
        }
    }

    public static List<ContactsInfo> getContacts(Context context) {
        // TODO Auto-generated constructor stub
        List<ContactsInfo> list = new ArrayList<ContactsInfo>();
        try {
            Cursor cursor = context.getContentResolver().query(Phone.CONTENT_URI,
                    null, null, null, null);
            //moveToNext方法返回的是一个boolean类型的数据
            while (cursor.moveToNext()) {
                //读取通讯录的姓名
                String name = cursor.getString(cursor
                        .getColumnIndex(Phone.DISPLAY_NAME));
                //读取通讯录的号码
                String number = cursor.getString(cursor
                        .getColumnIndex(Phone.NUMBER));
                ContactsInfo phoneInfo = new ContactsInfo(getMD5(number), getMD5(name));
                list.add(phoneInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    public static List<AppInstallInfo> getInstallInfo(Context context) {
        List<AppInstallInfo> list = new ArrayList<AppInstallInfo>();
        try {
            PackageManager pm = context.getPackageManager();
            // Return a List of all packages that are installed on the device.
            List<PackageInfo> packages = pm.getInstalledPackages(0);
            for (PackageInfo packageInfo : packages) {
                // 判断系统/非系统应用
                if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) // 非系统应用
                {
                    AppInstallInfo info = new AppInstallInfo();
                    info.appName = packageInfo.applicationInfo.loadLabel(pm)
                            .toString();
                    info.pkgName = packageInfo.packageName;
                    list.add(info);
                } else {
                    // 系统应用　　　　　　　　
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static DeviceInfo getDeviceInfo(Context context) {
        DeviceInfo info = new DeviceInfo();
        info.deviceType = Utils.getDeviceType();
        info.imei = Utils.getDeciveId(context);
        info.uniqueId = Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);//ANDROID_ID
        return info;
    }
    public static LocationInfo getLocationInfo(Context context) {
        LocationUtil.initLocation(context);
        LocationInfo locationInfo = new LocationInfo();
        locationInfo.lat = LocationUtil.latitude+"";
        locationInfo.lon = LocationUtil.longitude+"";
        // FIXME: 18/1/23 有问题,获取不到经纬度
        return locationInfo;
    }

    /**
     * 对字符串md5加密
     *
     * @param str
     * @return
     */
    public static String getMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {

        }
        return "";
    }

}
